import CloseIcon from '@/assets/close-1.png';
import ContentBg from '@/assets/draw-success.png';

import Prize115 from '@/assets/prize-115.png';
import Prize116 from '@/assets/prize-116.png';
import Prize117 from '@/assets/prize-117.png';
import Prize118 from '@/assets/prize-118.png';

import { useState } from 'react';
import { Overlay, Toast } from 'react-vant';

import { FillAddress, PRIZE_IDS, RewardDetail } from '@/apis/draw';
import SubmitButton from '@/assets/draw-submit.png';
import { useSetState } from 'ahooks';
import { useMutation } from 'umi';

export const PrizeImageMap = {
  [PRIZE_IDS.迪士尼门票]: { img: Prize115 },
  [PRIZE_IDS.背包]: { img: Prize116 },
  [PRIZE_IDS.贴纸]: { img: Prize117 },
  [PRIZE_IDS.盲盒]: { img: Prize118 },
};

export default function useSuccess(props?: { onSuccess?: Function }) {
  const [visible, setVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useSetState<{
    name: string | undefined;
    tel: string | undefined;
    address: string | undefined;
  }>({
    name: undefined,
    tel: undefined,
    address: undefined,
  });

  const { mutateAsync: mutateFillAddressAsync } = useMutation(FillAddress, {
    onSuccess: function () {
      mutateAsync({ id: detail?.id! });
    },
  });

  const { mutateAsync, data: detail } = useMutation(RewardDetail, {
    onSuccess: function () {
      setVisible(true);
    },
  });
  async function handleSubmitAddress() {
    if (!formValues.name) return Toast.fail('请输入姓名');
    if (!formValues.tel) return Toast.fail('请输入电话');
    if (formValues.tel.length !== 11) return Toast.fail('手机号格式不正确');
    if (!formValues.address) return Toast.fail('请输入地址');

    await mutateFillAddressAsync({
      name: formValues.name,
      phone: formValues.tel,
      address: formValues.address,
      id: detail?.id, // ?填写收货地址的时候关联中奖记录ID
    });

    Toast.success('提交成功');
    handleClose();
    props?.onSuccess && props.onSuccess();
  }

  async function handleClose() {
    formValues.name = undefined;
    formValues.tel = undefined;
    formValues.address = undefined;
    setVisible(false);
  }

  function renderNode() {
    return (
      <>
        <Overlay
          zIndex={99}
          visible={visible}
          className=" flex flex-col items-center pt-[100px]"
        >
          <div
            className="w-[646px] h-[1002px] bg-cover relative text-white text-center pt-[280px] text-sm"
            style={{
              backgroundImage: `url(${ContentBg})`,
            }}
          >
            <button
              onClick={() => handleClose()}
              className=" w-8 h-8 bg-cover absolute right-4 -top-8 active:scale-95"
              style={{
                backgroundImage: `url(${CloseIcon})`,
              }}
            />
            {detail?.lottery_result && (
              <>
                抽中了 <br /> {detail?.prize_name}
              </>
            )}

            {/* prize content */}
            <div className=" relative w-[300px] h-[300px] bg-[#f4f190] rounded-full border-4 border-white mt-4 mx-auto mb-4">
              {detail?.lottery_result && (
                <>
                  <img
                    src={PrizeImageMap[detail.lottery_result]?.img}
                    className="w-[380px] max-w-none absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
                    alt=""
                  />
                </>
              )}
            </div>
            {/* forms */}
            {(detail?.address && detail?.name && (
              <div className=" text-sm space-y-1 pt-3 px-8">
                <p>收件人:{detail?.name}</p>
                <p>联系方式:{detail?.phone}</p>
                <p>联系地址:{detail?.address}</p>
              </div>
            )) || (
              <div className=" text-[#3fa42b] text-sm  w-[380px] mx-auto space-y-2">
                <div className=" flex py-1 px-2 bg-[rgba(255,255,255,.8)]  rounded-md">
                  姓名:{' '}
                  <input
                    onChange={(e) => setFormValues({ name: e.target.value })}
                    type="text"
                    placeholder="请输入姓名"
                    className="ml-1 bg-transparent flex-1 block w-full "
                  />
                </div>

                <div className=" flex py-1 px-2 bg-[rgba(255,255,255,.8)]  rounded-md">
                  电话:{' '}
                  <input
                    onChange={(e) => setFormValues({ tel: e.target.value })}
                    type="tel"
                    maxLength={11}
                    placeholder="请输入电话"
                    className="ml-1 bg-transparent flex-1 block w-full "
                  />
                </div>

                <div className=" flex py-1 px-2 bg-[rgba(255,255,255,.8)]  rounded-md">
                  地址:{' '}
                  <input
                    onChange={(e) => setFormValues({ address: e.target.value })}
                    type="text"
                    placeholder="请输入地址"
                    className="ml-1 bg-transparent flex-1 block w-full "
                  />
                </div>
              </div>
            )}
          </div>

          {!detail?.address && (
            <button
              onClick={() => handleSubmitAddress()}
              className="w-[238px] h-[88px] bg-cover active:scale-95 mt-2"
              style={{
                backgroundImage: `url(${SubmitButton})`,
              }}
            />
          )}
        </Overlay>
      </>
    );
  }
  return {
    renderNode,
    open: async function (id: number) {
      if (!id) return Toast.fail('奖品记录ID不存在');
      const t = Toast.loading({ duration: 0 });

      // ?根据中奖记录ID查询奖品信息
      await mutateAsync({ id });
      t.clear();
    },
  };
}
